<template>
  <div class="resources-container">
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm">
        <el-form-item>
          <el-input v-model="searchForm.name" placeholder="资源名称" />
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchForm.status" placeholder="借用状态">
            <el-option label="全部状态" value="" />
            <el-option label="可借用" :value="1" />
            <el-option label="已借出" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            :shortcuts="dateShortcuts"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-row :gutter="20" class="resource-list">
      <el-col :span="6" v-for="resource in resourceStore.resources" :key="resource.id">
        <el-card :body-style="{ padding: '0px' }" class="resource-card">
          <el-carousel height="200px" v-if="resource.resourceImageInfo?.length">
            <el-carousel-item v-for="image in resource.resourceImageInfo" :key="image.id">
              <img :src="image.imageUrl" class="resource-image">
            </el-carousel-item>
          </el-carousel>
          <div class="resource-info">
            <h3>{{ resource.name }}</h3>
            <p class="description">{{ resource.description }}</p>
            <div class="meta">
              <span>发布者: {{ resource.userInfo.username }}</span>
              <el-tag :type="resource.status === 1 ? 'success' : 'info'">
                {{ resource.status === 1 ? '可借用' : '已借出' }}
              </el-tag>
            </div>
            <div class="actions">
              <el-button type="primary" @click="viewDetail(resource.id)">查看详情</el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[12, 24, 36, 48]"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useResourceStore } from '../stores/resource'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const resourceStore = useResourceStore()
const userStore = useUserStore()
const router = useRouter()

const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)

const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    },
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    },
  },
]

const searchForm = ref({
  name: '',
  status: '',
  dateRange: [],
  page: 1,
  pageSize: 12
})

const loadResources = async () => {
  const params = {
    name: searchForm.value.name,
    status: searchForm.value.status,
    page: currentPage.value,
    pageSize: pageSize.value,
    ownerId: userStore.userInfo.userId
  }
  
  // 如果选择了日期范围，添加开始和结束日期参数
  if (searchForm.value.dateRange?.length === 2) {
    params.beginTime = searchForm.value.dateRange[0] + ' 00:00:00'
    params.endTime = searchForm.value.dateRange[1] + ' 23:59:59'
  }
  
  console.log('请求参数:', params)
  
  const result = await resourceStore.getResources(params)
  if (result) {
    total.value = result.total
  }
}

const handleSearch = () => {
  currentPage.value = 1
  loadResources()
}

const resetSearch = () => {
  searchForm.value = {
    name: '',
    status: '',
    dateRange: [],
    page: 1,
    pageSize: 12
  }
  handleSearch()
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  loadResources()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  loadResources()
}

const viewDetail = (id: number) => {
  router.push(`/home/resource/${id}`)
}

const publishResource = async (formData: FormData) => {
  try {
    // 调试：打印 FormData 内容
    console.log('发送请求前的 FormData 内容:')
    for (let [key, value] of formData.entries()) {
      console.log(key, value instanceof File ? `File: ${value.name}` : value)
    }

    const response = await axios.post('/api/user/resource/pub', formData, {
      headers: {
        // 不要手动设置 Content-Type，让浏览器自动处理
        // 'Content-Type': 'multipart/form-data'
      }
    })
    
    console.log('请求响应:', response.data)
    return response.data.code === 1
  } catch (error: any) {
    console.error('发布资源请求错误:', error.response?.data || error)
    throw error
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      if (fileList.value.length === 0) {
        ElMessage.error('请上传至少一张图片')
        return
      }

      publishing.value = true
      try {
        const formData = new FormData()
        
        // 调试：打印原始表单数据
        console.log('原始表单数据:', form.value)
        
        // 确保所有字段都有值且类型正确
        formData.append('name', form.value.name || '')
        formData.append('categoryId', String(form.value.categoryId || ''))
        formData.append('location', form.value.location || '')
        formData.append('description', form.value.description || '')
        
        // 添加文件
        fileList.value.forEach(file => {
          if (file.raw) {
            formData.append('files', file.raw)
          }
        })

        // 调试：打印 FormData 内容
        console.log('发送前的 FormData 内容:')
        for (let [key, value] of formData.entries()) {
          console.log(key, value instanceof File ? `File: ${value.name}` : value)
        }

        try {
          const success = await resourceStore.publishResource(formData)
          if (success) {
            ElMessage.success('发布成功')
            router.push('/home/resources')
          }
        } catch (error: any) {
          console.error('发布失败:', error)
          ElMessage.error(error.response?.data?.msg || '发布失败，请重试')
        }
      } finally {
        publishing.value = false
      }
    }
  })
}

onMounted(() => {
  loadResources()
})
</script>

<style scoped>
.resources-container {
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 4px;
}

.resource-list {
  margin-bottom: 20px;
}

.resource-card {
  margin-bottom: 20px;
  transition: all 0.3s;
}

.resource-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
}

.resource-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

.resource-info {
  padding: 14px;
}

.resource-info h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.description {
  font-size: 13px;
  color: #909399;
  margin: 8px 0;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  font-size: 13px;
}

.actions {
  text-align: right;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style> 